package com.llmcu.source.javase.thread.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 用于感受：线程池会先填满队列，才会生成非核心线程
 *
 * @author liuling
 * @date 2024/11/25 20:00
 */
public class ExecutorServiceTest {
    public static void main(String[] args) {

        needIdle();
    }
    public static void needIdle(){
        ExecutorService executorService = new ThreadPoolExecutor(2,4,60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(2));
        // 最大线程数（核心线程数+非核心线程数）+队列长度=总任务时，核心线程拿了两个任务，队列放了两个任务，接着又创建了两个非核心线程
        for(int i=0;i<6;i++){
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getId()+"start task...");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getId()+"end task...");
            });
        }

    }
    public static void onlyCore(){
        ExecutorService executorService = new ThreadPoolExecutor(2,4,60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(2));
        // 核心线程数+队列长度=总任务时，核心线程处理完当前任务就去列列中拿新任务，没有创建新线程
        for(int i=0;i<4;i++){
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getId()+"start task...");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getId()+"end task...");
            });
        }
    }
}
